<template>
  <div class="riskScanning">
    <PageTitle :goBack="false" title="风险扫描" :border="false" />
    <div class="myTabs myFixed">
      <a-tabs v-model:activeKey="activeKey" @change="changeTab">
        <a-tab-pane :key="1" tab="风险扫描" />
        <a-tab-pane :key="2" tab="历史扫描记录" />
      </a-tabs>
    </div>
    <div class="main" v-show="activeKey === 1">
      <div class="myCardCss myCard">
        <div class="mySteps">
          <div class="steps">
            <a-steps type="navigation" :style="stepStyle">
              <a-step
                :status="current < 1 ? 'wait' : current === 1 ? 'process' : 'finish'"
                title="导入扫描企业名单"
              />
              <a-step
                :status="current < 2 ? 'wait' : current === 2 ? 'process' : 'finish'"
                title="匹配结果确认"
              />
              <a-step
                :status="current < 3 ? 'wait' : current === 3 ? 'process' : 'finish'"
                title="排查结果查看并导出"
              />
            </a-steps>
          </div>
          <div class="remarks">
            通过司法、监管、经营等多维度的风险排查，辅助您快速识别企业的失信被执行人、被执行人、限制高消费、裁判文书、开庭公告、行政处罚..等风险信息
          </div>
        </div>
      </div>
      <div class="myCardCss" style="margin-top: 8px; width: 100%" v-if="current === 1">
        <div class="upload-top">
          <div class="title">上传企业名单</div>
          <div>
            <a-button style="border-radius: 4px" type="primary" danger @click="downloadT"
              >下载导入模版</a-button
            >
          </div>
        </div>
        <div class="my-upload" v-if="!isLoading">
          <a-upload-dragger
            v-model:fileList="fileList"
            name="file"
            :multiple="false"
            action=""
            :beforeUpload="handleChange"
            :remove="removeFile"
          >
            <div class="ant-upload-hint">
              <div class="upload-icon">
                <img src="../../../assets/images/upload.png" alt="" />
              </div>
              <div class="upload-click">
                点击或将文件拖拽到这里上传
<!--                ，或-->
<!--                <a-button-->
<!--                  type="primary"-->
<!--                  danger-->
<!--                  style="margin: -5px 4px 0; border-radius: 4px"-->
<!--                  @click.stop="getHzTzlist"-->
<!--                  >点击此按钮</a-button-->
<!--                >-->
<!--                一键扫描已合作供应商-->
              </div>
            </div>
          </a-upload-dragger>
        </div>
        <div class="my-export" v-if="isLoading">
          <a-spin :indicator="isLoading" />
          <label>上传表格中，请等待...</label>
        </div>
        <div class="myTips">
          <div> · 文件不超过2M，仅支持Excel (xls、xlsx、csv) 文件；</div>
          <div> · 单次查询企业名称数量不超过 1000 家；</div>
          <div> · 可通过 排查记录 复用企业名单进行查询。</div>
        </div>
      </div>
      <div
        class="myCardCss"
        style="margin-top: 8px; width: 100%"
        v-if="current === 2 && !isLoading"
      >
        <div class="upload-top">
          <div class="title">匹配结果确认</div>
          <div> </div>
        </div>
        <div class="myTable">
          <a-table
            :dataSource="dataList"
            :columns="columns"
            :pagination="false"
            style="max-height: 500px"
          >
            <template #index="{ record, index }">
              {{ index + 1 }}
            </template>
            <template #match="{ record }">
              <label :style="{ color: record.match ? '#16AF44' : '#C11A20' }">{{
                record.match ? '成功' : '失败'
              }}</label>
            </template>
            <template #resultName="{ record }">
              <label :style="{ color: record.match ? '#16AF44' : '#C11A20' }">{{
                record.match ? record.companyName : '未找到企业'
              }}</label>
            </template>
            <template #operation="{ record, index }">
              <!-- <a-popconfirm
                title="是否确定移除?"
                ok-text="是"
                cancel-text="否"
                @confirm="confirmDel(index)"
                @cancel="cancelDel"
              > -->
              <a style="color: #1473dc" @click="openDelBox(index)">移除</a>

              <!-- </a-popconfirm> -->
            </template>
          </a-table>
        </div>
        <div class="myExportBtn">
          <a-button @click="exportTable">导出风险排查结果</a-button>
        </div>
      </div>
      <div class="myCardCss" style="margin-top: 8px; width: 100%" v-if="current === 2 && isLoading">
        <div class="upload-top">
          <div class="title">导出结果</div>
          <div> </div>
        </div>
        <div class="my-export">
          <a-spin :indicator="isLoading" />
          <label>导出中，请等待...</label>
        </div>
      </div>
      <div class="myCardCss" style="margin-top: 8px; width: 100%" v-if="current === 3">
        <div class="upload-top">
          <div class="title">导出结果</div>
          <div> </div>
        </div>
        <div class="my-download" v-if="!isLoading">
          <img src="../../../assets/images/success.png" alt="" />
          <label class="exportTips">导出成功，点击下载</label>
          <a-button
            type="primary"
            danger
            style="width: fit-content; margin: 16px auto 0"
            @click="downloadResult"
          >
            下载
          </a-button>
          <label class="tips">可前往历史扫描记录查看导出历史</label>
        </div>
        <div class="my-export" v-if="isLoading">
          <a-spin :indicator="isLoading" />
          <label>下载中，请等待...</label>
        </div>
      </div>
    </div>
    <div class="main" v-show="activeKey === 2">
      <div class="myCardCss" style="width: 100%">
        <a-table
          :dataSource="historyList"
          :columns="historyColumns"
          :pagination="false"
          :scroll="{ y: 550 }"
        >
          <template #index="{ record, index }">
            {{ (pageForm.limit - 1) * pageForm.size + index + 1 }}
          </template>
          <template #status="{ record }">
            {{
              record.status === 'INIT'
                ? '待执行'
                : record.status === 'FAILED'
                ? '导出失败'
                : record.status === 'EXECUTING'
                ? '执行中'
                : '导出成功'
            }}
          </template>
          <template #operation="{ record }">
            <a
              style="color: #1473dc"
              v-if="record.status === 'SUCCESS'"
              @click="downloadRecord(record.id, record.tableName)"
              >下载</a
            >
            <a
              style="color: #1473dc"
              v-else-if="record.status === 'FAILED'"
              @click="reSearch(record.id)"
              >重新查询</a
            >
            <a style="color: #1473dc" v-else>-</a>
          </template>
        </a-table>
      </div>
      <div class="otherPagination">
        <div class="seizeASeat"></div>
        <a-pagination
          size="small"
          :total="pageForm.total"
          :pageSize="pageForm.size"
          :current="pageForm.limit"
          :hideOnSinglePage="true"
          :showSizeChanger="false"
          @change="changePage"
          class="pag"
        />
      </div>
    </div>
    <!-- <DeleteBox
      :is-show="isShowDelBox"
      :ok-text="'确认取消'"
      :cancel-text="'我再想想'"
      :prompt-text="'取消后将错过企业最新动态！'"
      @ok="returnOk"
      @cancel="isShowDelBox = false"
    /> -->
    <a-modal v-model:visible="isShowDelBox" title="提示" @ok="handleOk">
      <div style="padding: 20px">是否确认移除</div>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { reactive, ref, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import PageTitle from '/@/components/PageTitle/index.vue';
  import {
    getHistoryPage,
    downloadData,
    reSearchRecord,
    submitData,
    getResult,
  } from '/@/api/riskInquiry';
  import { downloadTemple } from '/@/api/fileApi';
  import { getAppEnvConfig } from '/@/utils/env';
  import {getProjectLedger} from "/@/api/supplierManage";
  // import DeleteBox from '/@/components/DeleteBox/index.vue';
  let isShowDelBox = ref(false);
  let delId = ref(0);
  const openDelBox = (e) => {
    delId.value = e;
    isShowDelBox.value = true;
  };

  const handleOk = () => {
    confirmDel(delId.value);
    isShowDelBox.value = false;
  };
  const activeKey = ref(1);
  const current = ref<number>(1); // 步骤值
  const stepStyle = ref({
    marginBottom: '20px',
    fontSize: '12px',
  });
  function changeTab(val) {
    if (val === 2) {
      getHistoryList();
    }
  }
  const fileList = ref([]);
  let pageForm = ref({
    size: 10,
    limit: 1,
    total: 0,
  });
  function changePage(val) {
    pageForm.value.limit = val;
    // todo
    getHistoryList();
  }
  async function getHistoryList() {
    const queryData = {
      limit: pageForm.value.limit,
      size: pageForm.value.size,
    };
    let res = await getHistoryPage(queryData);
    historyList.value = res.list;
    pageForm.value.total = res.total;
  }
  // 下载纪录
  async function downloadRecord(recordId: string, tableName: string) {
    let res = await downloadData({ recordId });
    let url = window.URL.createObjectURL(res.data);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download = tableName;
    link.href = url;
    document.body.appendChild(link);
    link.click();
  }
  // 重新查询
  async function reSearch(recordId: string) {
    await reSearchRecord(recordId);
    getHistoryList();
  }
  let fileData = null;
  const handleChange = (file: any) => {
    fileData = file;
    fileList.value = [file];
    upLoadTable()
    return false;
  };
  const removeFile = () => {
    fileList.value = [];
    fileData = null;
  };
  let dataList = ref([]);
  let columns = ref([
    {
      title: '序号',
      align: 'center',
      slots: { customRender: 'index' },
    },
    {
      title: '企业名称',
      dataIndex: 'companyName',
      key: 'companyName',
      align: 'center',
    },
    {
      title: '匹配结果',
      dataIndex: 'match',
      key: 'match',
      align: 'center',
      slots: { customRender: 'match' },
    },
    {
      title: '匹配企业',
      dataIndex: 'resultName',
      key: 'resultName',
      align: 'center',
      slots: { customRender: 'resultName' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      slots: { customRender: 'operation' },
      align: 'center',
    },
  ]);
  let historyList = ref([]);
  let historyColumns = ref([
    {
      title: '序号',
      align: 'center',
      slots: { customRender: 'index' },
    },
    {
      title: '表格名称',
      dataIndex: 'tableName',
      key: 'tableName',
      align: 'center',
    },
    {
      title: '扫描时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
    },
    {
      title: '结果',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      slots: { customRender: 'status' },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      slots: { customRender: 'operation' },
      align: 'center',
    },
  ]);
  let submitFileName = '';
  // 上传
  function upLoadTable() {
    if (!fileData) {
      return message.warn('请选择要上传的文件');
    }
    isLoading.value = true;
    let action = getAppEnvConfig().VITE_GLOB_API_URL + '/risk/scan/upload';
    const formData = new FormData();
    formData.append('file', fileData);
    const xhr = new XMLHttpRequest();
    xhr.open('post', action, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
    xhr.onload = () => {
      const response = JSON.parse(xhr.response);
      if (response.code === 10500) {
        message.error('导入失败');
        fileData = null;
        fileList.value = [];
        isLoading.value = false;
      } else {
        message.success('导入成功');
        isLoading.value = false;
        current.value = 2;
        dataList.value = response.data?.companies;
        submitFileName = response.data.filename;
      }
    };
    xhr.onerror = () => {
      console.log('上传失败');
    };
    xhr.ontimeout = function timeout() {
      console.log('上传超时');
    };
    xhr.send(formData);
  }
  // 导出
  async function exportTable() {
    isLoading.value = true;
    let queryData = {
      filename: submitFileName,
      companyIds: dataList.value.map((item) => item.companyId),
    };
    const res = await submitData(queryData);
    smId = res;
    pollingGetState();
  }
  let smId = '';
  // 轮询获取扫描状态
  async function pollingGetState() {
    const res = await getResult({
      recordId: smId,
    });
    if (res.status === 'SUCCESS') {
      // 成功
      isLoading.value = false;
      current.value = 3;
    } else if (res.status === 'INIT') {
      // 执行中
      setTimeout(() => {
        pollingGetState();
      }, 5000);
    } else {
      // 失败
      message.error('扫描失败');
    }
  }
  // 下载
  async function downloadResult() {
    isLoading.value = true;
    let res = await downloadData({ recordId: smId });
    let url = window.URL.createObjectURL(res.data);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download = submitFileName;
    link.href = url;
    document.body.appendChild(link);
    link.click();
    isLoading.value = false;
    fileList.value = [];
    current.value = 1;
  }
  function confirmDel(index: number) {
    dataList.value.splice(index, 1);
    console.log('确定');
  }
  function cancelDel() {
    console.log('取消');
  }
  let isLoading = ref(false);
  async function downloadT() {
    let res = await downloadTemple('风险扫描模板.xlsx');
    let url = window.URL.createObjectURL(res.data);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download = '风险扫描模板.xlsx';
    link.href = url;
    document.body.appendChild(link);
    link.click();
  }
  async function getHzTzlist() {
    let queryData = {
      limit: 1,
      size: 100,
    };
    const res = await getProjectLedger(queryData);
    isLoading.value = false;
    current.value = 2;
    res.list.forEach((item : any) => {
      if (!dataList.value.filter((filItem: any) => filItem.companyId === item.companyId).length) {
        dataList.value.push({
          companyId: item.companyId,
          companyName: item.companyName,
          match: true
        })
      }
    })
    // dataList.value = res.list.map((item: any) => {
    //   return {
    //     companyId: item.companyId,
    //     companyName: item.companyName,
    //     match: true
    //   }
    // })
    submitFileName = '风险扫描.xlsx';

  }
</script>
<style lang="less" scoped>
  .riskScanning {
    :deep(.myTabs) {
      .ant-tabs-nav {
        background: #ffffff;
        margin-bottom: 0px !important;
        padding: 0 20px;
      }
    }
    :deep(.mySteps) {
      width: 100%;
      margin: 0 auto;
      border: 1px solid #dcdfe6;
      padding: 24px 120px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .ant-steps-navigation .ant-steps-item::before {
        height: 0;
      }
      .steps {
        padding: 0 170px;
      }
      .remarks {
        height: 38px;
        border-radius: 2px;
        background: #f5f7fa;
        text-align: center;
        line-height: 38px;
        color: #303133;
        font-size: 13px;
      }
    }
    .upload-top {
      display: flex;
      justify-content: space-between;
      .title {
        color: #303133;
        font-weight: 500;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
    .my-upload {
      margin-top: 12px;
      height: 354px;
      span {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
      .ant-upload-hint {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        height: 100%;
        .upload-icon {
          // border: 1px dashed #dcdfe6;
          margin-bottom: 12px;
        }
        .upload-click {
          display: flex;
          justify-content: center;
          color: #909399;
          font-size: 12px;
        }
      }
    }
    .myTips {
      margin-top: 12px;
      font-size: 12px;
      line-height: 20px;
      color: #606266;
    }
    .myTable {
      border: 1px solid #dcdfe6;
      margin-top: 16px;
    }
    .myExportBtn {
      display: flex;
      justify-content: center;
      padding-top: 12px;
    }
    .my-export {
      margin-top: 20px;
      width: 100%;
      height: 430px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      border: 1px dashed #dcdfe6;
      border-radius: 4px;
    }
    .my-download {
      margin-top: 20px;
      height: 430px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: center;
      border: 1px dashed #dcdfe6;
      border-radius: 4px;
      .exportTips {
        font-size: 16px;
        line-height: 24px;
        text-align: center;
        color: #303133;
      }
      img {
        width: 63px;
        height: 63px;
        margin: 0 auto 16px;
      }
      .tips {
        margin-top: 16px;
      }
    }
  }
  .otherPagination {
    float: right !important;
    width: 100%;
    height: 32px;
    background-color: #fff !important;
    display: flex;
    flex-direction: row-reverse;
  }
  .myFixed {
    position: fixed;
    z-index: 10;
    width: calc(100% - 258px);
    background: #ffffff;
  }
  .main{
    margin-top: 30px;
  }
</style>
